{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TensorFlow2教程-Variables\n",
    "\n",
    "TensorFlow 变量是表示程序所控制的共享持久状态的最佳方法。\n",
    "\n",
    "变量通过tf.Variable类进行操作。tf.Variable 表示张量，其值可以通过在其上运行ops进行更改。特定操作允许您读取和修改此张量的值。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 创建一个变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/doit/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=\n",
      "array([[1., 1., 1.],\n",
      "       [1., 1., 1.]], dtype=float32)>\n",
      "no gpu\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "# 要创建变量，只需提供初始值\n",
    "my_var = tf.Variable(tf.ones([2,3]))\n",
    "print(my_var)\n",
    "#如果tf.device作用域处于活动状态，则变量将被放置在该设备上；否则，变量将被放置在与其dtype兼容的“最快”设备上\n",
    "try:\n",
    "    with tf.device(\"/device:GPU:0\"):\n",
    "        v = tf.Variable(tf.zeros([10, 10]))\n",
    "        print(v)\n",
    "except:\n",
    "    print('no gpu')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 使用变量\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>\n",
      "tf.Tensor(9.0, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "# 变量相加\n",
    "a = tf.Variable(1.0)\n",
    "b = (a+2) *3\n",
    "print(a)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=3.0>\n",
      "tf.Tensor(9.0, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "# 更改某个向量\n",
    "a = tf.Variable(1.0)\n",
    "b = (a.assign_add(2)) *3\n",
    "print(a)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3 变量追踪\n",
    "TensorFlow中的变量是一个Python对象。在构建图层，模型，优化器和其他相关工具时，您可能希望获取（假设）模型中所有变量的列表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=10.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=0>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=2>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=4>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=6>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=7>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=8>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=9>)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class MyModuleOne(tf.Module):\n",
    "    def __init__(self):\n",
    "        self.v0 = tf.Variable(1.0)\n",
    "        self.vs = [tf.Variable(x) for x in range(10)]\n",
    "    \n",
    "class MyOtherModule(tf.Module):\n",
    "    def __init__(self):\n",
    "        self.m = MyModuleOne()\n",
    "        self.v = tf.Variable(10.0)\n",
    "    \n",
    "m = MyOtherModule()\n",
    "print(m.variables)  # 模型中的所有变量\n",
    "len(m.variables) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
